package com.shop.admin.dao.user;

import com.shop.jpa.BaseDao;
import com.shop.domain.user.User;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Repository
public interface UserDao extends BaseDao<User, Long> {

    //未中奖 添加佣金记录流水
    @Modifying(clearAutomatically = true)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Query(value = "update t_user u left join  t_store_pink p on p.uid = u.id set  u.brokerage = u.brokerage + ?2 " +
            " where p.pink_status=2 and  p.pink_id=?1 and p.is_deleted=0 and p.status=1 ",nativeQuery = true)
    int updateNotPz(Long pink_id,BigDecimal retPrice);

    @Modifying(clearAutomatically = true)
    @Query("update User set brokerage = brokerage + ?2 where id = ?1")
    public int addBrokerage(Long userId, BigDecimal brokerage);

    @Modifying(clearAutomatically = true)
    @Query("update User set balance = balance - ?2 where id = ?1 and balance - ?2 >= 0")
    public int subtractBalance(Long userId, BigDecimal balance);


    @Modifying(clearAutomatically = true)
    @Query("update User set level = ?2 where id = ?1")
    public int updateUserLevel(Long userId, Long level);


    @Query(nativeQuery = true, value = "select count(*) from t_user t where t.spread_uid=?1 and exists (select 1 from t_auto_pink a where a.uid = t.id) ")
    int queryAllCountFansBySpreadUid(Long userId);

    @Query(nativeQuery = true, value = "select count(*) from t_user t where t.spread_uid=?1 and level >0 ")
    int queryAllCountL1BySpreadUid(Long userId);

    @Query(nativeQuery = true, value = "select count(*) from t_user where FIND_IN_SET(?1, spreadids)  and level >0 ")
    int queryAllCountL1ToL5(Long userId);

    @Modifying(clearAutomatically = true)
    @Query("update User set integral = integral + ?2 where id = ?1")
    public int addIntegral(Long userId, BigDecimal integral);

    @Modifying(clearAutomatically = true)
    @Query("update User set integral = integral - ?2 where id = ?1 and integral - ?2 >= 0")
    public int subtractIntegral(Long userId, BigDecimal integral);


    //未中奖 添加返回余额
    @Modifying(clearAutomatically = true)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Query(value = "update t_user u left join  t_store_snap_pink p on p.uid = u.id set  u.balance = u.balance + ?2 " +
            " where p.pink_status=2 and  p.pink_id=?1 and p.is_deleted=0 and p.status=1 ",nativeQuery = true)
    int updateNotSnapPz(Long pink_id,BigDecimal retPrice);

}
